package cn.chendd.utils;

import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * <pre>
 * IO流关闭的工具类，关闭时判断是否为output输出流,如果为输出流则在关闭之前flush
 * </pre>
 *
 * <pre>
 * modify by chendd on 2016-8-2
 * </pre>
 */
public class CloseUtil {

	/**
	 * <pre>
	 * 关闭IO流
	 * </pre>
	 * @param close 流对象
	 */
	public static void close(Closeable close){
		
		if(close != null){
			try {
				if(close instanceof OutputStream){
					((OutputStream) close).flush();
				}
				close.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * <pre>
	 * 关闭一组流
	 * </pre>
	 * @param closes 流数组对象
	 */
	public static void close(Closeable ...closes){
		if(closes != null){
			for (Closeable closeable : closes) {
				close(closeable);
			}
		}
	}
	
	public static void close(ResultSet rs, Statement pst , Connection conn) {
		close(rs);
		close(pst);
		close(conn);
	}
	
	public static void close(ResultSet rs) {
		if(rs != null){
			try {
				rs.close();
				rs = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void close(Statement pst) {
		if(pst != null) {
			try {
				pst.close();
				pst = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void close(Connection conn) {
		if(conn != null){
			try {
				conn.close();
				conn = null;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
}
